package ui;

import base.Category;
import com.sun.lwuit.Button;
import com.sun.lwuit.Component;
import com.sun.lwuit.Container;
import com.sun.lwuit.Dialog;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.layouts.BoxLayout;
import db.CategoryManager;
import java.util.Vector;

/**
 *
 * @author Shayan
 */
public class CategorySelector extends Container implements ActionListener {

    private Vector categoris;
    private CategorySelectionListener listener;
    private String[] categoryIDs;

    public void setCategorySelectionListener(CategorySelectionListener listener) {
        this.listener = listener;
    }

    public CategorySelector() {
        try {
            categoris = CategoryManager.getAll();
            categoryIDs = new String[categoris.size()];
            setLayout(new BoxLayout(BoxLayout.Y_AXIS));
            for (int i = 0; i < categoris.size(); i++) {
                Category c = (Category) categoris.elementAt(i);
                categoryIDs[i] = c.getId();
                Button btn = new Button(c.getName());
                btn.addActionListener(this);
                btn.setUIID("CategotyButton");
                btn.setPreferredH(30);
                btn.setAlignment(CENTER);
                addComponent(btn);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            Dialog.show("Error", ex.toString(), "OK", "");
        }
    }

    public void actionPerformed(ActionEvent e) {
        Button btn = (Button) e.getSource();
        for (int i = 0; i < getComponentCount(); i++) {
            Component c = getComponentAt(i);
            if (c != btn) {
                // do something
            }
        }
        if (btn != null && listener != null) {
            listener.categorySelected(categoryIDs[getComponentIndex(btn)]);
        }
    }
}

